import json, io
from .utils import post
import ui
from .wrapper import subthread, withWaitSound
from . import settings
URL = 'http://web.juhe.cn:8080/finance/stock/hs?key=bd71403775e2159e810d4ca1230357e0&gid=%s'
# 查询接口
def getStockInfo(code):
    # 获取股票的信息，返回 html
    res = post(URL % code)
    if not res:
        raise Exception('No result.')
    # 解析原始数据
    data = json.loads(res)
    if not data:
        raise Exception('Parsing failed.')
    if int(data['resultcode']) != 200:
        raise Exception(data['reason'])
    result = data['result']
    if not result:
        raise Exception('No result.')
    buff = io.StringIO()
    for item in result:
        data, dapandata, gopicture = item['data'], item['dapandata'], item['gopicture']
        print(dapandata)
        # 名称和代码
        buff.write('<h1>%s(%s)</h1>' % (data['name'], data['gid']))
        # 基本信息
        buff.write('涨幅： %s(%s%%)<br />' % (data['increase'], data['increPer']))
        buff.write('今日： 开盘 %s， 最高 %s， 最低 %s<br />' % (data['todayStartPri'], data['todayMax'], data['todayMin']))
        buff.write('昨日收盘： %s<br />' % data['yestodEndPri'])
        buff.write('当前价格： %s<br />' % data['nowPri'])
        buff.write('竞买： %s； 竞卖： %s<br />' % (data['competitivePri'], data['reservePri']))
        buff.write('成交量： %s<br />' % data['traNumber'])
        buff.write('成交额： %.3fW<br />' % (float(data['traAmount']) / 10000))
        # 交易数据
        transact = data['buyOne'], data['buyOnePri'], data['buyTwo'], data['buyTwoPri'], data['buyThree'], data['buyThreePri'], data['buyFour'], data['buyFourPri'], data['buyFive'], data['buyFivePri'], data['sellOne'], data['sellOnePri'], data['sellTwo'], data['sellTwoPri'], data['sellThree'], data['sellThreePri'], data['sellFour'], data['sellFourPri'], data['sellFive'], data['sellFivePri']
        for i, field in enumerate(['买一', '买二', '买三', '买四', '买五', '卖一', '卖二', '卖三', '卖四', '卖五']):
            buff.write(f'{field}： {int(float(transact[i * 2]) / 100)}手， {transact[i * 2 + 1]}<br />')
        # 时间
        buff.write('日期： %s<br />' % data['date'])
        buff.write('时间： %s<br />' % data['time'])
        # K线图数据
        kLines = gopicture['minurl'], gopicture['dayurl'], gopicture['weekurl'], gopicture['monthurl']
        kLineNames = '分时', '日', '周', '月'
        for i, url in enumerate(kLines):
            buff.write('<img src="%s" alt="%sK线图" /><br />' % (url, kLineNames[i]))
    res = buff.getvalue()
    buff.close()
    if not res:
        raise Exception('No result.')
    return res
currentStock = 0 #当前股票序号
@withWaitSound
@subthread
def viewStock():
    global currentStock
    # 读取用户关注的股票列表
    codeList = settings.getViewStock()
    code = codeList[currentStock]
    # 循环切换股票的处理
    currentStock += 1
    if currentStock >= len(codeList):
        currentStock = 0
    if not code:
        ui.message(_('请先在设置中添加股票代码。'))
        return
    try:
        res = getStockInfo(code)
        ui.browseableMessage(res, '股票详情', True)
    except Exception as e:
        ui.message(_(f'{e}'))